<?php
class YouNet_View_Helper_PageUrl extends Zend_View_Helper_Abstract {

	private $_search	= '';
	private $_hash		= '';
	private $_2parent	= false;
	public function pageUrl(array $params = array(), $reset = false, $encode = true)
	{
		$request			= Zend_Controller_Front::getInstance()->getRequest();
		$this->_hash		= '';
		$this->_search		= '';
		$this->_2parent		= false;

		foreach($params as $key => $value)
		{
			if( is_array($value) )
			{
				$k	= key($value);
				$v	= current($value);
				if( $request->getParam($key) == $k )
				{
					$params[$key] = $v;
				}
				else
				{
					unset($params[$key]);
				}
			}
		}
		if( empty($params['id_page']) )
		{
			$params['id_page'] = $request->getParam(
				'id_page',
				YouNet_Api::getInstance()->getSocialPlugin()->getIdPage()
			);
		}
		if( isset($params['_query_string']) )
		{
			$this->_search = $params['_query_string'];
		}
		if( isset($params['_search']) )
		{
			$this->_search = $params['_search'];
		}
		if( !empty($params['_full']) && empty($this->_search))
		{
			if( !empty($_SERVER['QUERY_STRING']) )
			{
				$this->_search = $_SERVER['QUERY_STRING'];
			}
		}
		if( isset($params['_hash']) )
		{
			$this->_hash = $params['_hash'];
		}
		if( isset($params['_target'])
			&& in_array($params['_target'],array('top', 'parent'))
		)
		{
			$this->_2parent = true;
		}
		foreach($params as $key => $value)
		{
			if( $key[0] === '_' )
			{
				unset($params[$key]);
			}
		}
		if( $this->_2parent )
		{
			return $this->parent($params);
		}
		return $this->iframe($params, $reset, $encode);
	}

	protected function iframe(array $params = array(), $reset = false, $encode = true)
	{
		$url = $this->view->url($params, 'tab', $reset, $encode);
		if( !empty($this->_search) )
		{
			$url .= '?'.$this->_search;
		}
		if( !empty($this->_hash) )
		{
			$url .= '#'.$this->_hash;
		}
		return $url;
	}

	protected function parent(array $params = array())
	{
		$request		= Zend_Controller_Front::getInstance()->getRequest();
		$params			= array_merge($request->getUserParams(), $params);
		$systemParams	= array(
								$request->getModuleKey(),
								$request->getControllerKey(),
								$request->getActionKey()
						);
		foreach($systemParams as $param)
		{
			if( isset($params[$param]) )
			{
				unset($params[$param]);
			}
		}
		if( $this->_search )
		{
			$params = array_merge($params, $_GET);
		}
		return YouNet_Api::getInstance()->getSocialPlugin()->pageUrl($params);
	}
}
